<template>
  <div class="Lo">
     <div class="HH">
      <h1>手机登录</h1>
        <div class="register-wrapper" :default-active="$route.path" router>
            <div id="register">
                <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleFormRef" label-width="0"
                    class="demo-ruleForm">
                    
                    <el-form-item  prop="tel">
                        <el-input v-model="ruleForm.tel"  auto-complete="off" placeholder="请输入手机号"
                            :prefix-icon="Iphone">
                        </el-input>
                    </el-form-item>
                    <!-- 验证码 -->
                    <div style="width: 120px;position: relative;left: 60px;margin-bottom: 15px;">
                      <PicVerify ></PicVerify>
                      <input type="text" v-model="ruleForm.pic" placeholder="请输入验证码" style="width:200px;height: 40px;position:absolute;float: left; top: 0px;left: 160px;border: 1px solid silver;color: darkgray;text-align: center;"/>
                    </div>
                    <el-form-item prop="smscode" class="code">
                        <el-input v-model="ruleForm.smscode" placeholder="请输入验证码" :prefix-icon="Tickets" ></el-input>
                        <el-button type="primary" :disabled='isDisabled' @click="sendCode" class="yzm">{{ buttonText}}</el-button>
                        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)" >登录</el-button>
                    </el-form-item>

                </el-form>
            </div>
        </div>
    </div>
  </div>

</template>

<script lang="ts" setup>
import {useRoute,useRouter} from 'vue-router'
import {
  Iphone,
  PhoneFilled,
  Tickets,
} from "@element-plus/icons-vue";
import { reactive, ref ,inject} from 'vue'
import type { FormInstance } from 'element-plus'
import PicVerify from '../save/picVerify.vue';
import { ElMessage } from 'element-plus'

const ruleFormRef = ref<FormInstance>()


//通过注入的方法来获取axios实例
const $http:any=inject('$http') 
//定义路由器
const $router=useRouter()
const $route=useRoute()

const counter = ref(0)
const flag = ref(true)
const buttonText = ref('发送验证码')
const isDisabled = ref(false)

const ruleForm = reactive({
  tel: '',
  smscode: '',
  pic:'',
})

//校验手机号--------------------------------------------------------
const checkTel = (rule: any, value: any, callback: any) => {
  const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
  if (value === '') {
    callback(new Error('请输入手机号码'))
  } else if (value.length <= 10 || !reg.test(value)) {
    callback(new Error('手机号码不合法'))
  } else {
    callback()
  }
}
//校验手机验证码
const checkSmscode = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机验证码'))
  } else {
    callback()
  }
}
//校验验证码
const checkPic = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else {
    callback()
  }
}
const rules = reactive({
   tel: [{ validator: checkTel, trigger: 'change' }],
   smscode: [{ validator: checkSmscode, trigger: 'change' }],
   pic: [{ validator: checkPic, trigger: 'change' }],
})
//校验---------------------------------------------------------

//发送验证码
const sendCode=()=>{
    if (ruleForm.tel!=''&& ruleForm.pic!='') {
      const sendTel = {
        phoneNum:ruleForm.tel,
      }
      console.log(ruleForm.tel)
                let time = 60
                buttonText.value = '已发送'
                isDisabled.value = true
                if (flag) {
                    flag.value = false;
                    let timer = setInterval(() => {
                        time--;
                        buttonText.value = time + ' 秒'
                        if (time === 0) {
                            clearInterval(timer);
                            buttonText.value = '重新获取'
                            isDisabled.value = false
                            flag.value = true;
                        }
                    }, 1000)
      
         login(sendTel)
      }
    } else {
      ElMessage({
        message: '验证失败，请重试',
        type: 'error',
    })
    }
  
  //调用方法请求后端
  async function login(sendTel) {
    let { data } = await $http.post('/sendCode', sendTel);
    if(data.code == 20071){
      ElMessage({
        message: '发送成功，请注意查收验证码',
        type: 'success',
    })
    }else{
      resetForm
      ElMessage({
        message: '发送失败，请重试',
        type: 'error',
    })
    }
  }
}

//表单提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
   formEl.validate(async (valid) => {
    if (valid) {
      const sendData = {
        phoneNum:ruleForm.tel,
        SmsCode:ruleForm.smscode,
      }
      login(sendData)
    } else {
      console.log('登录失败,请重试')
      return false
    }
  })
  //调用方法请求后端
  async function login(sendData) {
    let { data } = await $http.post('/sendCode', sendData);
    if(data.code == 20071){
      console.log("登录成功");
        //保存token
        let token=JSON.stringify(data.data)
        window.localStorage.setItem('token',token)
        //$router.push('/xxx')
    }else{
      resetForm
      alert('登录失败,请重试')
      console.log("登录失败");
    }
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style scoped>
    .Lo{
      width: 100%;
      height: 400px;
    }
    .HH{
      position: absolute;
      z-index: 0;
      width: 460px;
    }
    h1{
      text-align: center;
    }
    :deep(.el-button+.el-button){
      position: relative;
      float: left;
     width: 20%;
     left: 160px;
     margin-left: 30px;
     margin-top: 25px;
    }
    .rememberMe{
      left: 170px;
    }
    :deep(.el-button){
      margin-top: 25px;
       height: 45px;
    }
    :deep(.el-input){
      height: 50px;
      width: 80%;
      left: 60px;
    }
    .yzm{
      left: 60px;
      top: 50px;
      position: absolute;
    }

</style>